package com.lgh.hotel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lgh.hotel.dao.mapper.SysUserMapper;
import com.lgh.hotel.dao.pojo.SysUser;
import com.lgh.hotel.service.RolesService;
import com.lgh.hotel.service.SysUserService;
import com.lgh.hotel.utils.JWTUtils;
import com.lgh.hotel.vo.Result;
import com.lgh.hotel.vo.SysUserVo;
import com.lgh.hotel.vo.UserVo;
import com.lgh.hotel.vo.params.PageParams;
import com.lgh.hotel.vo.params.SysUserParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    BCryptPasswordEncoder encoder;

    @Autowired
    RolesService rolesService;
    @Override
    public Result registered(SysUserParams sysUserParams,String token) {
        System.out.println(sysUserParams);
        Map<String, Object> map = JWTUtils.checkToken(token);
        SysUser sysUser = new SysUser();
        String userId = (String) map.get("userId");
        sysUser.setFounder(userId);
        sysUser.setStatus(0);
        sysUser.setDeteled(0);
        sysUser.setCreationTime(System.currentTimeMillis());
        SysUser sysUser1 = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, sysUserParams.getUsername()));
        if (sysUser1 != null){
            return Result.fail("已有用户！");
        }
        sysUser.setUsername(sysUserParams.getUsername());
        sysUser.setPassword(encoder.encode(sysUserParams.getPassword()));
        sysUser.setNickname(sysUserParams.getNickname());
        sysUser.setRoles("3");
        sysUser.setEmail(sysUserParams.getEmail());
        sysUser.setPhoneNumber(Long.parseLong(sysUserParams.getPhoneNumber()));
        return Result.succ(sysUserMapper.insert(sysUser));
    }

    @Override
    public SysUser findUserByUsername(String username) {
        return sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
    }

    @Override
    public SysUser findUserByToken(String token) {

        if (token == null || token.length() == 0) {
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map ==null){
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson == null){
            return null;
        }
        return JSONObject.parseObject(userJson,SysUser.class);
    }

    @Override
    public SysUserVo findUserByInfoVo(String token) {
        SysUser userByToken = findUserByToken(token);
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setName(userByToken.getNickname());
        sysUserVo.setAvatar(userByToken.getAvatar());
        String s = rolesService.findRolesById(userByToken.getRoles());
        List<String> strings = rolesService.findRolesByTypeAll(Integer.parseInt(userByToken.getRoles()));
        sysUserVo.setRoutes(strings);
        sysUserVo.setRoles(s);
        return sysUserVo;
    }

    @Override
    public Result logoutUser(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.succ("success");
    }

    @Override
    public Result findUserAll() {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.orderByDesc(SysUser::getCreationTime);
        queryWrapper.orderByAsc(SysUser::getCreationTime);
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
        return Result.succ(sysUsers);
    }

    @Override
    public Result findUserBy(String type, String params) {
        if (params == null || params.length() <=0){
            return null;
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (type.equals("1")){
            queryWrapper.like(params!="***", SysUser::getUsername, "%"+params+"%");
//            queryWrapper.eq(SysUser::getUsername,params);
            return Result.succ(sysUserMapper.selectList(queryWrapper));
        }
        queryWrapper.eq(SysUser::getPhoneNumber,params);
        return Result.succ(sysUserMapper.selectOne(queryWrapper));
    }

    @Override
    public Result findUserPageList(PageParams params) {
        Page<SysUser> page = new Page<>(params.getPage(), params.getPageSize());
//        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.orderByDesc(SysUser::getCreationTime);
        Page<SysUser> sysUserPage = sysUserMapper.selectPage(page,null);
//        List<UserVo> userVos = copyList(sysUserPage);
//        sysUserPage.setRecords(userVos);

        return Result.succ(sysUserPage);
    }

    private List<UserVo> copyList(Page<SysUser> sysUserPage) {
        List<UserVo> userVos = new ArrayList<>();
        List<SysUser> records = sysUserPage.getRecords();
        for (SysUser record : records) {
            userVos.add(copy(record));
        }
        return userVos;
    }

    private UserVo copy(SysUser record) {
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(record,userVo);
        userVo.setId(record.getId().toString());
        userVo.setPhoneNumber(record.getPhoneNumber().toString());
        return userVo;
    }

    @Override
    public Result updateUser(SysUser sysUserParams, String token) {
        return Result.succ(sysUserMapper.updateById(sysUserParams));
    }

    @Override
    public Result deleteUser(Long id) {
        return Result.succ(sysUserMapper.deleteById(id));
    }

    @Override
    public Result findEmployees() {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getRoles, 2);
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
        return Result.succ(sysUsers);
    }

    @Override
    public Result findEmployeesPages(PageParams params) {

        Page<SysUser> sysUserPage = new Page<>(params.getPage(),params.getPageSize());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getRoles, 3);
        Page<SysUser> sysUserPage1 = sysUserMapper.selectPage(sysUserPage, queryWrapper);
        return Result.succ(sysUserPage1);

    }

}
